package com.yyy;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

import java.util.concurrent.Callable;

/**
 * @author HeJinYang
 */
public class SessionServer implements Callable<Channel> {
    private Channel channel = null;

    // 服务端启动
    private static NioEventLoopGroup parentGroup = new NioEventLoopGroup();
    private static NioEventLoopGroup ioGroup = new NioEventLoopGroup();

    @Override
    public Channel call() throws Exception {
        ChannelFuture channelFuture = new ServerBootstrap().group(parentGroup, ioGroup)
                .option(ChannelOption.SO_BACKLOG, 128)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new HttpRequestDecoder());
                        pipeline.addLast(new HttpResponseEncoder());
                        pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
                        pipeline.addLast(new SessionServerHandler());
                    }
                }).bind(9996).syncUninterruptibly();
        channel = channelFuture.channel();

        return channel;
    }
}
